package com.mall.shopping.services;

import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class ICartServiceImpl implements ICartService {
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    static Integer temp1 = null;

    /**
     * 展示商品首页
     * @param request
     * @return
     */
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();
        //CartProductDto cartProductDto = new CartProductDto();
        ArrayList<CartProductDto> cartProductDtos = new ArrayList<>();

        RMap<Integer, CartListShowDTO> map = redissonClient.getMap(request.getUserId().toString());
        for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            //System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            Long tempProductId = Long.parseLong(entry.getValue().getProductId().toString());
            Long tempProductNum = Long.parseLong(entry.getValue().getProductNum().toString());
            Long tempLimitNum = Long.parseLong(entry.getValue().getLimitNum().toString());
            CartProductDto cartProductDto = new CartProductDto(tempProductId,entry.getValue().getSalePrice(),tempProductNum,tempLimitNum,entry.getValue().getChecked().toString(),entry.getValue().getProductName(),entry.getValue().getProductImg());
            cartProductDtos.add(cartProductDto);
        }
        cartListByIdResponse.setCartProductDtos(cartProductDtos);
        cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());

        return cartListByIdResponse;
    }

    /**
     * 数据存入购物车，进行合并
     * @param request
     * @return
     */
    @Override
    public synchronized AddCartResponse addToCart(AddCartRequest request) {
        //
        /*Member member = memberMapper.selectByPrimaryKey(request.getUserId());
        member.getUsername();*/
        //
        //String str = request.getUserId();
        String userId = String.valueOf(request.getUserId());
        Boolean flag = true;
        //就是把数据存到redis中
        RMap<Integer, CartListShowDTO> map = redissonClient.getMap(userId);

        Item item = itemMapper.selectByPrimaryKey(request.getItemId());
        Integer temp = Integer.valueOf(item.getId().toString());
        Integer tempItemId = Integer.valueOf(request.getItemId().toString());

        //如果里面有商品就加一，没有商品就创建

        for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            //如果购物车有商品，就替换加一，因为每次只调动一次

            if (entry.getKey().equals(tempItemId)){
                //说明有商品，有商品就加一
                temp1 = tempItemId;
                CartListShowDTO cartListShowDTO = new CartListShowDTO(entry.getValue().getProductId(),item.getPrice(),entry.getValue().getProductNum()+1,item.getLimitNum(),entry.getValue().getChecked(),item.getTitle(),item.getImage());
                map.replace(tempItemId,cartListShowDTO);

            } else if (!entry.getKey().equals(tempItemId)){
                if (temp1 !=tempItemId){
                CartListShowDTO cartListShowDTO = new CartListShowDTO(temp,item.getPrice(),request.getNum(),item.getLimitNum(),flag,item.getTitle(),item.getImage());
                map.put(temp,cartListShowDTO);
                }
            }
        }
        if (map.size() == 0){
            CartListShowDTO cartListShowDTO = new CartListShowDTO(temp,item.getPrice(),request.getNum(),item.getLimitNum(),flag,item.getTitle(),item.getImage());
            map.put(temp,cartListShowDTO);
        }
        //错误的原因在于把上面元素覆盖掉了
        //数据没有合并
        //如果里面没有这个数据，就新建立一个
       /* for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            if (entry.getKey() !=temp){
                CartListShowDTO cartListShowDTO = new CartListShowDTO(temp,item.getPrice(),request.getNum(),item.getLimitNum(),flag,item.getTitle(),item.getImage());
                map.put(temp,cartListShowDTO);
            }
        }*/

        AddCartResponse response = new AddCartResponse();
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        return response;
    }

    //修改订单状态
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        request.getUserId();
        RMap<Integer, CartListShowDTO> map = redissonClient.getMap(request.getUserId().toString());
        Item item = itemMapper.selectByPrimaryKey(request.getItemId());
        Integer temp = Integer.valueOf(request.getItemId().toString());
        Boolean flag = false;
        if (request.getChecked()!=null){
            if (request.getChecked().equals("true")){
                flag = true;
            }else if (request.getChecked().equals("false")){
                flag = false;
            }
        }
        CartListShowDTO cartListShowDTO = new CartListShowDTO(temp,item.getPrice(),request.getNum(),item.getLimitNum(),flag,item.getTitle(),item.getImage());

        for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
        map.replace(temp,cartListShowDTO);
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        return response;
    }

    /**
     * 全选 应该是按一下就全不选
     * @param request
     * @return
     */
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        request.getChecked();
        request.getUserId();
        Boolean temp = false;
        if ( request.getChecked().equals("true")){
            temp = true;
        }else if ( request.getChecked().equals("false")){
            temp = false;
        }

        RMap<Integer, CartListShowDTO> map = redissonClient.getMap(request.getUserId().toString());
        for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());

            CartListShowDTO cartListShowDTO = new CartListShowDTO(entry.getKey(),entry.getValue().getSalePrice(),entry.getValue().getProductNum(),entry.getValue().getLimitNum(),temp,entry.getValue().getProductName(),entry.getValue().getProductImg());
            map.replace(entry.getKey(),cartListShowDTO);
        }
        CheckAllItemResponse response = new CheckAllItemResponse();
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        request.getUserId();
        request.getItemId();
        RMap<Integer, CartListShowDTO> map = redissonClient.getMap(request.getUserId().toString());
        //map.remove(request.getItemId());
        for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            Integer temp = Integer.valueOf(request.getItemId().toString());
            if (entry.getKey().equals(temp)){
                map.remove(entry.getKey(),entry.getValue());
            }
        }

        DeleteCartItemResponse response = new DeleteCartItemResponse();
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        //删除商品怎么删，根据key删除VALUE
        return response;
    }

    /**
     * 删除选中商品
     * @param request
     * @return
     */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        request.getUserId();//71已经有了
        String strUserId = String.valueOf(request.getUserId());
        RMap<Integer, CartListShowDTO> map = redissonClient.getMap(strUserId);
        for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            //里面都是 boolean true类型的参数
          //  map.remove(entry.getKey(),entry.getValue());
            Boolean temp = entry.getValue().getChecked();
            //是true说明被选中
            if (temp){
                boolean remove = map.remove(entry.getKey(), entry.getValue());
            }
        }

        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        return response;
    }

    //选中的商品进行付款
    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        //把选中的商品进行删除
        request.getUserId();
        //如果map里有商品，就把他删除掉
        List<Long> productIds = request.getProductIds();
        RMap<Integer, CartListShowDTO> map = redissonClient.getMap(request.getUserId().toString());
        for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            Long intToLong = Long.parseLong(entry.getKey().toString());
            for (Long productId : productIds) {
                if (productId.equals(intToLong)){
                    map.remove(entry.getKey(),entry.getValue());
                    break;
                }
            }
        }
        ClearCartItemResponse response = new ClearCartItemResponse();
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        return response;
    }
}
